/*
 * @Author       : NaN 353362604@qq.com
 * @Date         : 2023-04-16 13:54:29
 * @LastEditTime : 2023-04-23 14:04:38
 * @LastEditors  : NaN 353362604@qq.com
 * @FilePath     : \AdminStration\src\Pages\Admin\Assembly\MenuList.jsx
 * @Description  :
 */
import { Menu, Spin } from 'antd'
import { useEffect, useState } from 'react'
import { ICON } from '../../../Common/Configure/Icon'
import { useEventEmitter, useSessionStorageState } from 'ahooks'
import { useCallback } from 'react'

export const Menu001 = ({ OpenMenuStatus, SelectMenusEvent, SelectMenus }) => {
    const [MENU] = useSessionStorageState('MENU')
    const [loading, setLoading] = useState(true)
    const getItem = ({ uuid, icon, tableName, isEnabled, targetUrl, pageType }) => ({
        key: uuid,
        icon: icon,
        label: tableName,
        enabled: isEnabled,
        url: targetUrl,
        pagetype: pageType,
    })
    const [items, setItem] = useState([])
    const getMenu = useCallback(menu => {
        let menuData = []
        menu.forEach(({ type, tableName, uuid, icon, children, isEnabled, targetUrl, pageType }) => {
            if (type === 0 && isEnabled !== 0) {
                let data = getItem({ uuid, icon: ICON[icon] || null, tableName, isEnabled, targetUrl, pageType })
                if (children && children.length !== 0)
                    if (getMenu(children).length !== 0) data.children = getMenu(children)
                menuData = [...menuData, data]
            } else if (type === 2 && isEnabled !== 0) menuData = [...menuData, ...getMenu(children)]
        })
        return menuData
    }, [])

    useEffect(() => {
        setItem(getMenu(MENU))
        setLoading(false)
    }, [MENU, getMenu])

    const [OpenKeyArr, setOpenKeyArr] = useState([])

    const OpenChangeEvent = useEventEmitter()
    window.OpenChangeEvent = OpenChangeEvent
    OpenChangeEvent.useSubscription(val => {
        const { type, value } = val
        if (type === 'open') {
            setOpenKeyArr(e => [...e, value])
        } else {
            setOpenKeyArr(OpenKeyArr.filter(item => item !== value))
        }
    })

    return (
        <div className="Menu001">
            <Spin spinning={loading}>
                <Menu
                    openKeys={OpenKeyArr}
                    selectedKeys={[SelectMenus]}
                    inlineCollapsed={!OpenMenuStatus}
                    inlineIndent={24}
                    mode="inline"
                    theme="light"
                    items={items}
                    onClick={({ key }) => SelectMenusEvent.emit(key)}
                    onOpenChange={e => {
                        console.log('展开事件', e)
                        setOpenKeyArr(e)
                    }}
                />
            </Spin>
        </div>
    )
}
